package com.nl.controller.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.Response;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.PDF.PdfReport;
import com.nl.controller.web.service.SmsReportDetailService;
import com.nl.controller.web.bean.SmsReportDetail;
import com.nl.controller.web.util.ExcelUtil;
import com.nl.controller.web.util.FileUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("smsReportDetail")
public class SmsReportDetailController {

    @Autowired
    private SmsReportDetailService smsReportDetailService;

    @ApiOperation(value = "短信发送明细查询", notes = "短信发送明细查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "way", value = "时间段查询方式", required = true, dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "发送起始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "发送结束时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "month", value = "发送的月份", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrId", value = "项目名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "regionId", value = "区域编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "stationId", value = "基站编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cityId", value = "城市编码", required = true, dataType = "String")
    })
    @PostMapping("find")
    public Response findReportDetail(
            @RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "way", required = false) String way,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "month", required = false) String month,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam(value = "receiver", required = false) String receiver,
            @RequestParam(value = "regionId", required = false) String regionId,
            @RequestParam(value = "stationId", required = false) String stationId,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam Map<String, Object> paramMap
    ) {
        if ("".equals(cityId) || cityId == null) {
            throw new SmsException("请选择查询条件，开始查询");
        } else {
            PageInfo<SmsReportDetail> pageInfo;
            pageInfo = smsReportDetailService.findSmsInfo(page, limit, cityId, way, month, startTime, endTime, mgrId, receiver, mgrName, regionId, stationId, countyId);
            log.info("短信项目明细参数：{}",paramMap.toString());
            log.debug("短信项目明细返回数据：{}",pageInfo.getList().toString());
            return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
        }
    }


    @ApiOperation(value = "短信发送明细查询", notes = "查询项目下的区域")
    @PostMapping("findRegionInfo")
    private Response findRegionInfo(@RequestParam(value = "mgrId") String mgrId,
                                    @RequestParam(value = "cityId") String cityId) {
        List<SmsReportDetail> list = smsReportDetailService.findRegionInfo(mgrId, cityId);
        log.info("查询项目下的区域：{}",mgrId);
        log.debug("查询项目下的区域返回数据：{}",list.size());
        return ResponseUtil.sucess(list);
    }

    @ApiOperation(value = "短信发送明细查询", notes = "查询区域下的基站")
    @PostMapping("findStationInfo")
    private Response findStationInfo(@RequestParam(value = "regionId") String regionId, @RequestParam(value = "cityId") String cityd, @RequestParam(value = "mgrId") String mgrId) {
        List<SmsReportDetail> list = smsReportDetailService.findStationInfo(regionId, cityd, mgrId);
        log.info("查询区域下的基站：{}",mgrId);
        log.debug("查询区域下的基站返回数据：{}",list.size());
        return ResponseUtil.sucess(list);
    }



    @GetMapping("/download")
    @ApiOperation(value = "明细导出", notes = "查询项目下的区域")
    public void partExport(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "cityId", required = false) String cityId,
                           @RequestParam(value = "way", required = false) String way,
                           @RequestParam(value = "startTime", required = false) String startTime,
                           @RequestParam(value = "endTime", required = false) String endTime,
                           @RequestParam(value = "month", required = false) String month,
                           @RequestParam(value = "mgrId", required = false) String mgrId,
                           @RequestParam(value = "regionId", required = false) String regionId,
                           @RequestParam(value = "stationId", required = false) String stationId,
                           @RequestParam(value = "countyId", required = false) String countyId) {
        //含有基站使用普通的导出方式
       if (regionId != null && !"".equals(regionId)) {
            String title = "短信明细表.pdf";
            JSONArray ja = smsReportDetailService.download(way, month, startTime, endTime, mgrId, regionId, stationId,cityId,countyId);
            List<SmsReportDetail> list = smsReportDetailService.download2(way, month, startTime, endTime, mgrId, regionId, stationId,cityId,countyId);
           new PdfReport().createPdfReport2(list);
           goToDownload(request, response, title);
           log.info("---生成pdf成功---");
            log.info("导出开始");
            //ExcelUtil.downloadExcelFile(title, headMap, ja, response,request);
            log.info("导出结束");
            log.debug("明细表导出的数据{}", ja.size());
        } //没有基站，使用下载文件的方式
        else {
            try {
                List<File> list;
                log.info("导出开始");
                list=smsReportDetailService.fileDownload(cityId,way, month, startTime, endTime, mgrId);
                FileUtil.downLoadFiles(list,request,response);
                log.info("导出结束");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("文件下载失败");
            }
        }
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @param fileName 下载文件的名称
     */
    private void goToDownload(HttpServletRequest request, HttpServletResponse response, String fileName) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        try {
            String encodenickname = URLEncoder.encode(fileName, "UTF-8");//转Unicode不然ie会乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(encodenickname.getBytes("UTF-8"), "ISO8859-1"));
            //这里注掉的代码是本地测试的
//            String path = request.getSession().getServletContext().getRealPath("/");
//            String ATTACH_PATH= AppConfig.getInstance().getProperty("attach.base","");
//            if (StringUtils.isNotEmpty(ATTACH_PATH)) {
//                path = ATTACH_PATH;
//            }
//            logger.debug("=path===" + path);
            File file = new File("D:\\欢迎名片报表文件.pdf");
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            long fileLength = file.length();
            response.setHeader("Content-Length", String.valueOf(fileLength));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



